package cn.bluethink.timescaledb.mapper;

import cn.bluethink.timescaledb.entity.Dynamic;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DynamicRowMapper implements RowMapper {

    private List<String> keys;

    @Override
    public Object mapRow(ResultSet resultSet, int i) throws SQLException {
        Dynamic dynamic = new Dynamic();
        dynamic.setTime(resultSet.getDate("time"));
        dynamic.setNumber(resultSet.getInt("number"));
        List<Map<String, String>> locations = new ArrayList<>();
        for (int j = 0; j < keys.size(); j++) {
            Map<String, String> location = new HashMap<>();
            if (!keys.get(j).equals("time") && !keys.get(j).equals("number")) {
                String locationFromTable = resultSet.getString(keys.get(j));
                location.put(keys.get(j), locationFromTable);
                locations.add(location);
            }
        }
        dynamic.setLocation(locations);
        return dynamic;
    }

    public DynamicRowMapper(List<String> keys) {
        this.keys = keys;
    }

    public List<String> getKeys() {
        return keys;
    }

    public void setKeys(List<String> keys) {
        this.keys = keys;
    }

}
